﻿<%@ WebHandler Language="C#" Class="user" %>

using System;
using System.Web;
using System.Web.SessionState;
using System.Collections.Generic;
using System.Linq;

using Newtonsoft.Json;
using VISS.Web.Frontend;
using NCT.Framework;
using VISS.API.Users;
using VISS.MailImpl;

public class user : IHttpHandler, IRequiresSessionState {

    private const int MaxFileSizeUpload = 6 * 1024 * 1024; // 6M
    private static string[] fileTypes = { ".jpg", ".jpeg", ".png" };

    private delegate void DelSendMail(UserEnt userEnt, UserGeneralProfileEnt userGenProfileEnt);

  
    
    private void SendMail(UserEnt userEnt, UserGeneralProfileEnt userGenProfileEnt) {
        MailEnt.MailRegisterSuccess ent = new MailEnt.MailRegisterSuccess();
        ent.Subject = "VISS - Thư kích hoạt tài khoản";
        ent.Email = userEnt.Email;
        ent.FullName = userGenProfileEnt.Name;
        ent.Password = userEnt.Password;
        ent.UserKey = userEnt.UserKey;
        MailEnt.MailInfo mailInfo = new MailEnt.MailInfo();
        mailInfo.MailContent = SerializerUtils.JsonSerialize(ent);
        mailInfo.SendMailType = ESendMailType.RegisterSuccess;

        try {
            if (NCT.Mail.MailQueuePD.CreateInstance().AddToQueue(AppSettings.MailType, SerializerUtils.JsonSerialize(mailInfo)) <= 0) {
                LogUtils.Error("Sent mail:frontend.viss.vn: active user fail.");
            }
        }
        catch (Exception ex) {
            LogUtils.Error("Sent mail fail: " + ex.ToString());
        }
    }

    public void ProcessRequest(HttpContext context) {
        string action = context.Request.Form["action"];
        switch (action) {
            case "login":
                Login(context);
                break;
            case "logout":
                Logout(context);
                break;
            case "createUser":
                CreateUser(context);
                break;
            case "createEmail":
                CreateEmail(context);
                break;
            case "saveBlast":
                SaveBlast(context);
                break;
            case "savePassword":
                SavePassword(context);
                break;
            case "saveGeneral":
                SaveGeneral(context);
                break;
            case "savePersonal":
                SavePersonal(context);
                break;
            case "saveGeneralCondition":
                SaveGeneralCondition(context);
                break;
            case "changeAvatar":
                ChangeAvatar(context);
                break;
            case "uploadImages":
                UploadImages(context);
                break;
            case "deleteImage":
                DeleteImage(context);
                break;
            case "changeAvatarByImage":
                ChangeAvatarByImage(context);
                break;
            case "sendMessage":
                SendMessage(context);
                break;
            case "replyMessage":
                ReplyMessage(context);
                break;
            case "deleteConversation":
                DeleteConversation(context);
                break;
            case "deleteMessage":
                DeleteMessage(context);
                break;
            case "sendReport":
                SendReport(context);
                break;
            case "addFollow":
                AddFollow(context);
                break;
            case "deleteFollow":
                DeleteFollow(context);
                break;
            case "changeStatus":
                ChangeStatus(context);
                break;
        }
    }

    private void Login(HttpContext context) {
        string result = "{{\"result\":\"{0}\",\"content\":\"{1}\"}}";
        string username = context.Request.Form["username"];
        string password = context.Request.Form["password"];
        string url = context.Request.Form["url"];

        UserContext userSC;
        EUserLoginResult rs = LoginFactory.Login(username, password, false, out userSC);
        switch (rs) {
            case EUserLoginResult.WrongEmail://2
                FormValidateUtils.Return(string.Format(result, 2, ""));
                break;
            case EUserLoginResult.WrongPassword://3
                FormValidateUtils.Return(string.Format(result, 3, ""));
                break;
            case EUserLoginResult.Disabled://5
                FormValidateUtils.Return(string.Format(result, (int)EUserLoginResult.Disabled, ""));
                break;
            case EUserLoginResult.Deleted://6
                FormValidateUtils.Return(string.Format(result, (int)EUserLoginResult.Deleted, ""));
                break;
            case EUserLoginResult.Success://1
                context.Session["STATUSUS"] = null;
                if (url == null || url == "") {
                    url = AppSettings.RootURL + "profile?u=" + userSC.UserKey;
                }
                FormValidateUtils.Return(string.Format(result, (int)EUserLoginResult.Success, url));
                break;
            case EUserLoginResult.Unknown://7
                FormValidateUtils.Return(string.Format(result, (int)EUserLoginResult.Unknown, ""));
                break;
        }
    }

    private void Logout(HttpContext context) {
        string result = "{{\"result\":\"{0}\"}}";
        LoginFactory.Logout();
        FormValidateUtils.Return(string.Format(result, "1"));
    }

    /// <summary>
    /// 0: Lỗi hệ thống
    /// 1: Thành công
    /// 2: Tỉ lệ hình không đúng
    /// 3: Kích thước file không đúng
    /// 4: Kích thước hình không đúng
    /// 5: Định dạng file không đúng
    /// </summary>
    /// <param name="context"></param>
    private void ChangeAvatar(HttpContext context) {
        UserContext userContext = LoginFactory.GetCurrentUser();
        if (userContext == null) {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write("<script type='text/javascript'>");
            HttpContext.Current.Response.Write("window.parent.uploadAvatarComplete('-1','');window.close();");
            HttpContext.Current.Response.Write("</script>");
            return;
        }
        string result = "1";
        string avatarPath = string.Empty;
        EUploadImageResult uploadResult = UploadAvatar(context, userContext.UserKey, userContext.DateCreated);
        if (uploadResult == EUploadImageResult.Success) {
            result = "1"; //Success
            avatarPath = LoginFactory.RefeshAvatarPath(userContext.UserKey, userContext.Gender);
            userContext.AvatarPath = avatarPath;
        }
        else {
            switch(uploadResult) {
                case EUploadImageResult.SystemError:
                    result = "0";
                    break;
                case EUploadImageResult.InvalidHeight:
                case EUploadImageResult.InvalidWidth:
                    result = "2";
                    break;
                case EUploadImageResult.InvalidFileSize:
                    result = "3";
                    break;
                case EUploadImageResult.InvalidImageSize:
                    result = "4";
                    break;
                case EUploadImageResult.InvalidFileExtension:
                    result = "5";
                    break;
            }
        }
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Write("<script type='text/javascript'>");
        HttpContext.Current.Response.Write("window.parent.uploadAvatarComplete('" + result + "','" + avatarPath + "');window.close();");
        HttpContext.Current.Response.Write("</script>");
    }

    private void CreateEmail(HttpContext context) {
        string email = Commons.StripAllTag(context.Request.Form["email"]);
        _TmpEmailDA.Insert(new _TmpEmailEnt() { Email = email });
    }

    private void CreateUser(HttpContext context) {
        string fullname = Commons.StripAllTag(context.Request.Form["Fullname"]);
        fullname = Commons.NormalizeName(fullname);
        string sex = context.Request.Form["Sex"];
        string iWantMale = context.Request.Form["IwantMale"];
        string iWantFemale = context.Request.Form["IwantFemale"];

        string birthday = context.Request.Form["Birthday"];
        string cityID = context.Request.Form["City"];
        string jobID = context.Request.Form["Job"];
        string email = string.Empty;
        if (context.Session["OPENID"] != null)
            email = context.Session["OPENID"].ToString();
        else
            email = Commons.StripAllTag(context.Request.Form["Email"]);
        string phone = Commons.StripAllTag(context.Request.Form["Phone"]);
        string aboutMe = Commons.StripAllTag(context.Request.Form["Introduce"]);
        aboutMe = Commons.BreakWords(aboutMe, 10);
        if(aboutMe.Length == 0) {
            aboutMe = "Chào mừng bạn đến với ViSS";
        }
        string[] datetime;
        int day, month, year;

        if (string.IsNullOrEmpty(fullname) ||
            string.IsNullOrEmpty(sex) ||
            string.IsNullOrEmpty(birthday) ||
            string.IsNullOrEmpty(cityID) ||
            string.IsNullOrEmpty(jobID) ||
            string.IsNullOrEmpty(email) ||
            (iWantMale != "1" && iWantFemale != "1")) {
            ReturnForRegister("Bạn hãy cung cấp đầy đủ những thông tin yêu cầu");
            return;
        }
        if (fullname.Length < 6) {
            ReturnForRegister("Họ tên phải lớn hơn 6 ký tự");
            return;
        }
        if (email.IndexOfAny(new char[] { '@', '.' }) == -1) {
            ReturnForRegister("Email của bạn không hợp lệ");
            return;
        }
        if (sex != "1" && sex != "0") {
            ReturnForRegister("Giới tính không hợp lệ");
            return;
        }
        if(!Commons.IsNumber(phone)) {
            ReturnForRegister("Số điện thoại di động không hợp lệ");
            return;
        }
        datetime = birthday.Split('/');
        if (datetime.Length < 3 &&
            !char.IsNumber(datetime[0], 0) &&
            !char.IsNumber(datetime[1], 0) &&
            !char.IsNumber(datetime[2], 0)) {
            ReturnForRegister("Ngày sinh phải theo định dạng: Ngày / Tháng / Năm");
            return;
        }
        else if (DateTime.Now.Year - ConvertUtils.ToDateTime(birthday, "d/M/yyyy").Year < 18) {
            ReturnForRegister("Vui lòng kiểm tra lại ngày sinh. ViSS chỉ dành cho người trên 18 tuổi");
            return;
        }
        if (aboutMe.Length > AppSettings.LengthBlast) {
            ReturnForRegister("Tự giới thiệu phải nhỏ hơn " + AppSettings.LengthBlast + " ký tự");
            return;
        }
        if (BabWordFilter.ContainsBadWords(aboutMe)) {
            ReturnForRegister("Nội dung tự giới thiệu không được chứa từ ngữ thô tục");
            return;
        }

        IUser _objectUser = StructureMapFactory.GetInstance<IUser>();
        ECheckEmailResult rs = _objectUser.CheckEmailExisted(email);
        switch (rs) {
            case ECheckEmailResult.Exist:
                ReturnForRegister(ECheckEmailResult.Exist.ToString());//1
                break;
            case ECheckEmailResult.NotExist:
                UserEnt userEnt = new UserEnt();
                UserGeneralProfileEnt userGenProfileEnt = new UserGeneralProfileEnt();
                UserContactInfoEnt userContactEnt = new UserContactInfoEnt();
                userContactEnt.MobiPhone = phone;
                userEnt.Email = email;

                day = ConvertUtils.ToInt(datetime[0]);
                month = ConvertUtils.ToInt(datetime[1]);
                year = ConvertUtils.ToInt(datetime[2]);

                userGenProfileEnt.Blast = aboutMe;
                userGenProfileEnt.BirthDate = new DateTime(year, month, day);
                userGenProfileEnt.CityID = ConvertUtils.ToShort(cityID);
                userGenProfileEnt.JobID = ConvertUtils.ToShort(jobID);
                userGenProfileEnt.Gender = (EUserGender)ConvertUtils.ToInt(sex);
                userGenProfileEnt.Name = fullname;
                if (iWantFemale == "1" && iWantMale == "1")
                    userGenProfileEnt.LookingFor = EUserLookingFor.All;
                else if (iWantFemale == "1")
                    userGenProfileEnt.LookingFor = EUserLookingFor.Female;
                else if (iWantMale == "1")
                    userGenProfileEnt.LookingFor = EUserLookingFor.Male;

                if (_objectUser.Insert(userEnt, userGenProfileEnt, userContactEnt)) {

                    //Thực hiện gửi mail
                    DelSendMail del = new DelSendMail(SendMail);
                    del.BeginInvoke(userEnt, userGenProfileEnt, null, null);

                    //Thực hiện upload avatar
                    //Bỏ qua thông báo nếu xảy ra lỗi
                    UploadAvatar(context, userEnt.UserKey, userEnt.DateCreated);
                }
                else {
                    ReturnForRegister("fail");
                    return;
                }
                context.Session["STATUSUS"] = userContactEnt.Email; //"CREATED";
                if (context.Session["OPENID"] != null) {
                    if (_objectUser.UpdateStatus(userEnt.UserKey, EUserStatus.Actived)) {
                        context.Session["OPENID"] = null;
                        UserContext userContext;
                        EUserLoginResult rsLoginOpenID = LoginFactory.LoginOpenID(email, false, out userContext);
                        if (rsLoginOpenID == EUserLoginResult.Success) {
                            HttpContext.Current.Response.ClearContent();
                            HttpContext.Current.Response.ContentType = "text/html";
                            HttpContext.Current.Response.Write("<script language='javascript' type='text/javascript'>");
                            HttpContext.Current.Response.Write("window.parent.location = '" + AppSettings.RootURL + "profile?u=" + userContext.UserKey + "';");
                            HttpContext.Current.Response.Write("</script>");
                            return;
                        }
                        else if (rsLoginOpenID == EUserLoginResult.Unknown) {
                            ReturnForRegister(ECheckEmailResult.Unknown.ToString());//0
                            return;
                        }
                    }
                    else {
                        ReturnForRegister(ECheckEmailResult.Unknown.ToString());//0
                        return;
                    }
                }
                ReturnForRegister("success");
                break;
            case ECheckEmailResult.Unknown:
                ReturnForRegister(ECheckEmailResult.Unknown.ToString());//0
                break;
        }
    }

    private EUploadImageResult UploadAvatar(HttpContext context, string userKey, DateTime userCreatedDate) {
        EUploadImageResult result;
        if (!string.IsNullOrEmpty(context.Request.Files[0].FileName)) {
            string ext = "";
            string fileNameAvatar = context.Request.Files[0].FileName;
            int index = fileNameAvatar.LastIndexOf(".");
            if (index > 0) {
                ext = fileNameAvatar.Substring(index);
                fileNameAvatar = fileNameAvatar.Substring(0, index);
            }
            if (!fileTypes.Contains(ext.ToLower())) {
                return EUploadImageResult.InvalidFileExtension;
            }

            if (context.Request.Files[0].ContentLength > MaxFileSizeUpload) {
                return EUploadImageResult.InvalidFileSize;
            }

            System.IO.Stream st = context.Request.Files[0].InputStream;

            ImageInfo imageInfo = NCT.Framework.ImageUtils.GetInfo(st);

            if (imageInfo.Width < AppSettings.AvatarMinRequireWidth && imageInfo.Height < AppSettings.AvatarMinRequireHeight) {
                return EUploadImageResult.InvalidImageSize;
            }

            result = AvatarUploadHandle(context, userKey, userCreatedDate, st);

            if (result == EUploadImageResult.Success) {
                ImageUploadHandle(context, userKey, userCreatedDate, st);
            }
        }
        else {
            return EUploadImageResult.EmptyFileError;
        }
        return result;
    }

    /// <summary>
    /// Save password
    /// -1: Chưa đăng nhập
    /// 1: Lưu mật khẩu thành công
    /// 2: Bạn hãy hoàn tất thông tin trên
    /// 3: Mật khẩu cũ không đúng
    /// 4: Độ dài mật khẩu không đúng
    /// 5: Xác nhận mật khẩu không khớp
    /// 0: Lỗi hệ thống
    /// </summary>
    /// <param name="context"></param>
    private void SavePassword(HttpContext context) {
        UserContext userContext = LoginFactory.GetCurrentUser();
        string result = "{{\"result\":\"{0}\"}}";

        if (userContext == null) {
            result = "{{\"result\":\"{0}\"}}";
            FormValidateUtils.Return(string.Format(result, "-1", AppSettings.RootURL + "login"));
            return;
        }

        string oldPassword = context.Request.Form["oldPassword"];
        string newPassword = context.Request.Form["newPassword"];
        string confirmNewPassword = context.Request.Form["confirmNewPassword"];

        if (
            oldPassword == string.Empty ||
            newPassword == string.Empty ||
            confirmNewPassword == string.Empty) {
            FormValidateUtils.Return(string.Format(result, "2"));
            return;
        }

        IUser _objectUser = StructureMapFactory.GetInstance<IUser>();
        UserEnt userEnt = null;
        userEnt = _objectUser.GetByUserKey(userContext.UserKey);
        if (userEnt == null) {
            FormValidateUtils.Return(string.Format(result, "0"));
            return;
        }

        if (userEnt.Password != StringUtils.DoMD5(oldPassword)) {
            FormValidateUtils.Return(string.Format(result, "3"));
            return;
        }

        if (newPassword.Length < 6 || newPassword.Length > 32) {
            FormValidateUtils.Return(string.Format(result, "4"));
            return;
        }

        if (newPassword != confirmNewPassword) {
            FormValidateUtils.Return(string.Format(result, "5"));
            return;
        }
        if (!_objectUser.UpdatePassword(userEnt.UserKey, newPassword)) {
            FormValidateUtils.Return(string.Format(result, "0"));
        }

        FormValidateUtils.Return(string.Format(result, "1"));
    }

    /// <summary>
    /// Save General
    /// -1: Bạn không vui lòng đăng nhập để thực hiện chức năng này.
    ///  1: Lưu thông tin cá nhân thành công
    ///  2: Bạn hãy hoàn tất thông tin trên
    ///  3: Họ tên không hợp lệ
    ///  4: Giới tính không hợp lệ
    ///  5: Định dạng ngày sinh không đúng
    ///  6: Ngày sinh không hợp lệ
    ///  7: City không hợp lệ
    ///  0: Lỗi hệ thống!
    /// </summary>
    /// <param name="context"></param>
    private void SaveGeneral(HttpContext context) {
        string result = "{{\"result\":\"{0}\"}}";
        UserContext userContext = LoginFactory.GetCurrentUser();
        if (userContext == null) {
            FormValidateUtils.Return(string.Format(result, "-1"));
            return;
        }
        string fullName;
        if ((userContext.Status & EUserStatus.Verified) == EUserStatus.Verified) {
            fullName = userContext.FullName;
        }
        else {
            fullName = Commons.StripAllTag(context.Request.Form["fullName"]);
            fullName = Commons.NormalizeName(fullName);
        }
        string birthday = context.Request.Form["birthday"];
        string sex = context.Request.Form["sex"];
        string cityID = context.Request.Form["cityID"];

        string[] datetime;

        short sCityID = ConvertUtils.ToShort(cityID);

        if (string.IsNullOrEmpty(fullName) ||
        string.IsNullOrEmpty(birthday) ||
        string.IsNullOrEmpty(sex) ||
        string.IsNullOrEmpty(cityID)) {
            FormValidateUtils.Return(string.Format(result, "2"));
            return;
        }
        if (fullName.Length < 6) {
            FormValidateUtils.Return(string.Format(result, "3"));
            return;
        }
        if (sex != "1" && sex != "0") {
            FormValidateUtils.Return(string.Format(result, "4"));
            return;
        }
        if (sCityID <= 0) {
            FormValidateUtils.Return(string.Format(result, "7"));
            return;
        }
        datetime = birthday.Split('/');
        if (datetime.Length < 3 &&
            !char.IsNumber(datetime[0], 0) &&
            !char.IsNumber(datetime[1], 0) &&
            !char.IsNumber(datetime[2], 0)) {
            FormValidateUtils.Return(string.Format(result, "5"));
            return;
        }
        else if (DateTime.Now.Year - ConvertUtils.ToDateTime(birthday, "d/M/yyyy").Year < 18) {
            FormValidateUtils.Return(string.Format(result, "6"));
            return;
        }

        IUserGeneralProfile iUserGeneralProfile = StructureMapFactory.GetInstance<IUserGeneralProfile>();
        UserGeneralProfileEnt userGeneralProfile = iUserGeneralProfile.GetByUserKey(userContext.UserKey);

        userGeneralProfile.Name = fullName;
        userGeneralProfile.BirthDate = ConvertUtils.ToDateTime(birthday, "d/M/yyyy");
        userGeneralProfile.Gender = (EUserGender)ConvertUtils.ToByte(sex);
        userGeneralProfile.CityID = ConvertUtils.ToShort(cityID);

        if (!iUserGeneralProfile.UpdateWithoutBlast(userGeneralProfile)) {
            FormValidateUtils.Return(string.Format(result, "0"));
            return;
        }
        else {
            //Update User Context
            userContext.FullName = fullName;
            userContext.Gender = userGeneralProfile.Gender;
            LoginFactory.SetUserSession(userContext);
        }

        FormValidateUtils.Return(string.Format(result, "1"));
    }

    /// <summary>
    /// Save Personal
    /// -1: Bạn không vui lòng đăng nhập để thực hiện chức năng này.
    ///  1: Lưu thông tin cá nhân thành công
    ///  2: Bạn hãy hoàn tất thông tin trên
    ///  3: Chiều cao và cân nặng phải là số
    ///  4: Chiều cao không hợp lệ
    ///  5: Cân nặng không hợp lệ
    ///  6: Hobby không hợp lệ
    ///  7: Income không hợp lệ
    ///  8: Education không hợp lệ
    ///  9: Job không hợp lệ
    ///  10: Religion không hợp lệ
    ///  11: Smoking không hợp lệ
    ///  12: MaritalStatus không hợp lệ
    ///  0: Lỗi hệ thống!
    /// </summary>
    /// <param name="context"></param>
    private void SavePersonal(HttpContext context) {
        string result = "{{\"result\":\"{0}\"}}";
        UserContext userContext = LoginFactory.GetCurrentUser();
        if (userContext == null)
            FormValidateUtils.Return(string.Format(result, "-1"));
        else {
            string height = context.Request.Form["height"];
            string weight = context.Request.Form["weight"];
            string religionID = context.Request.Form["religionID"];
            string jobID = context.Request.Form["jobID"];
            string educationID = context.Request.Form["educationID"];
            string income = context.Request.Form["inCome"];
            string maritalStatusID = context.Request.Form["maritalStatusID"];
            string smokingID = context.Request.Form["smokingID"];
            string iWantMale = context.Request.Form["iWantMale"];
            string iWantFemale = context.Request.Form["iWantFemale"];
            string hobby = Commons.StripAllTag(context.Request.Form["hobby"]);
            hobby = Commons.BreakWords(hobby, 10);

            if (string.IsNullOrEmpty(height) ||
                string.IsNullOrEmpty(weight) ||
                string.IsNullOrEmpty(religionID) ||
                string.IsNullOrEmpty(jobID) ||
                string.IsNullOrEmpty(educationID) ||
                string.IsNullOrEmpty(income) ||
                string.IsNullOrEmpty(maritalStatusID) ||
                string.IsNullOrEmpty(smokingID) ||
                string.IsNullOrEmpty(iWantMale) ||
                string.IsNullOrEmpty(iWantFemale) ||
                string.IsNullOrEmpty(hobby)) {
                FormValidateUtils.Return(string.Format(result, "2"));
                return;
            }

            short sHeight = ConvertUtils.ToShort(height);
            short sWeight = ConvertUtils.ToShort(weight);
            short sEducationID = ConvertUtils.ToShort(educationID);
            short sJobID = ConvertUtils.ToShort(jobID);
            short sReligionID = ConvertUtils.ToShort(religionID);
            short sSmokingID = ConvertUtils.ToShort(smokingID);
            short sMaritalStatusID = ConvertUtils.ToShort(maritalStatusID);
            int iIncome = ConvertUtils.ToInt(income);

            //Nếu Height,Weight jobID, educationID không là số
            if (sHeight == 0 || sWeight == 0) {
                FormValidateUtils.Return(string.Format(result, "3"));
                return;
            }
            if (sHeight > AppSettings.MaxHeight || sHeight < AppSettings.MinHeight) {
                FormValidateUtils.Return(string.Format(result, "4"));
                return;
            }
            if (sWeight > AppSettings.MaxWeight || sWeight < AppSettings.MinWeight) {
                FormValidateUtils.Return(string.Format(result, "5"));
                return;
            }
            if (hobby.Length > AppSettings.LengthHobby || hobby.Length == 0) {
                FormValidateUtils.Return(string.Format(result, "6"));
                return;
            }
            if (!Commons.IsNumber(income) || !SelectCtrlBuilder.InComeList.Contains(income)) {
                FormValidateUtils.Return(string.Format(result, "7"));
                return;
            }
            if(sEducationID <= 0) {
                FormValidateUtils.Return(string.Format(result, "8"));
                return;
            }
            if (sJobID <= 0) {
                FormValidateUtils.Return(string.Format(result, "9"));
                return;
            }
            if (sReligionID <= 0) {
                FormValidateUtils.Return(string.Format(result, "10"));
                return;
            }
            if (sSmokingID <= 0) {
                FormValidateUtils.Return(string.Format(result, "11"));
                return;
            }
            if (sMaritalStatusID <= 0) {
                FormValidateUtils.Return(string.Format(result, "12"));
                return;
            }
            if (BabWordFilter.ContainsBadWords(hobby)) {
                FormValidateUtils.Return(string.Format(result, "14"));
                return;
            }

            IUserGeneralProfile iUserGeneralProfile = StructureMapFactory.GetInstance<IUserGeneralProfile>();
            UserGeneralProfileEnt userGeneralProfile = iUserGeneralProfile.GetByUserKey(userContext.UserKey);
            userGeneralProfile.JobID = sJobID;
            userGeneralProfile.EducationID = sEducationID;
            if (iWantMale == "1" && iWantFemale == "1")
                userGeneralProfile.LookingFor = EUserLookingFor.All;
            else if (iWantFemale == "1")
                userGeneralProfile.LookingFor = EUserLookingFor.Female;
            else if (iWantMale == "1")
                userGeneralProfile.LookingFor = EUserLookingFor.Male;
            userGeneralProfile.Hobby = hobby;

            IUserFamilyProfile iUserFamilyProfile = StructureMapFactory.GetInstance<IUserFamilyProfile>();
            UserFamilyProfileEnt userFamilyProfileEnt = iUserFamilyProfile.GetByUserKey(userContext.UserKey);
            userFamilyProfileEnt.MaritalStatusID = sMaritalStatusID;

            IUserCultureProfile iUserCultureProfile = StructureMapFactory.GetInstance<IUserCultureProfile>();
            UserCultureProfileEnt userCultureProfileEnt = iUserCultureProfile.GetByUserKey(userContext.UserKey);
            userCultureProfileEnt.ReligionID = sReligionID;

            IUserAppearanceProfile iUserAppearanceProfile = StructureMapFactory.GetInstance<IUserAppearanceProfile>();
            UserApperanceProfileEnt userApperanceProfileEnt = iUserAppearanceProfile.GetByUserKey(userContext.UserKey);
            userApperanceProfileEnt.Weight = sWeight;
            userApperanceProfileEnt.Height = sHeight;

            IUserLivingProfile iUserLivingProfile = StructureMapFactory.GetInstance<IUserLivingProfile>();
            UserLivingProfileEnt userLivingProfileEnt = iUserLivingProfile.GetByUserKey(userContext.UserKey);
            userLivingProfileEnt.Income = iIncome;
            userLivingProfileEnt.SmokingID = sSmokingID;

            //begin Insert To Database
            bool a = iUserGeneralProfile.UpdateWithoutBlast(userGeneralProfile);
            bool b = iUserFamilyProfile.Update(userFamilyProfileEnt);
            bool c = iUserCultureProfile.Update(userCultureProfileEnt);
            bool d = iUserAppearanceProfile.Update(userApperanceProfileEnt);
            bool e = iUserLivingProfile.Update(userLivingProfileEnt);
            if (a && b && c && d && e != true) {
                FormValidateUtils.Return(string.Format(result, "0"));
            }
            
            //Update User Context
            userContext.LookingFor = userGeneralProfile.LookingFor;
            LoginFactory.SetUserSession(userContext);
            
            //end  Insert To Database
            FormValidateUtils.Return(string.Format(result, "1"));
            return;
        }
    }
    
    /// <summary>
    /// Save General Condition
    /// -1: Chưa đăng nhập
    /// 1: Thành công
    /// 2: Giới hạn Tuổi không hợp lệ
    /// 3: Giới hạn Chiều Cao không hợp lệ
    /// 4: Giới hạn Cân nặng không hợp lệ
    /// 0: Lỗi hệ thống
    /// </summary>
    /// <param name="context"></param>
    private void SaveGeneralCondition(HttpContext context) {
        string result = "{{\"result\":\"{0}\"}}";
        
        UserContext userContext = LoginFactory.GetCurrentUser();
        if (userContext == null) {
            FormValidateUtils.Return(string.Format(result, "-1"));
            return;
        }

        byte minOld = ConvertUtils.ToByte(context.Request.Form["minOld"], 0);
        byte maxOld = ConvertUtils.ToByte(context.Request.Form["maxOld"], 0);
        short minHeight = ConvertUtils.ToShort(context.Request.Form["minHeight"], 0);
        short maxHeight = ConvertUtils.ToShort(context.Request.Form["maxHeight"], 0);
        short minWeight = ConvertUtils.ToShort(context.Request.Form["minWeight"], 0);
        short maxWeight = ConvertUtils.ToShort(context.Request.Form["maxWeight"], 0);
        int inCome = ConvertUtils.ToInt(context.Request.Form["inCome"], -1);
        string cityID = ConvertUtils.ToString(context.Request.Form["cityID"], "-1");
        string jobID = ConvertUtils.ToString(context.Request.Form["jobID"], "-1");
        short educationID = ConvertUtils.ToShort(context.Request.Form["educationID"], -1);
        short religionID = ConvertUtils.ToShort(context.Request.Form["religionID"], -1);
        short maritalStatusID = ConvertUtils.ToShort(context.Request.Form["maritalStatusID"], -1);
        short smokingID = ConvertUtils.ToShort(context.Request.Form["smokingID"], -1);

        if (minOld > 0 && maxOld > 0 && minOld > maxOld) {
            FormValidateUtils.Return(string.Format(result, "2"));
            return;
        }

        if (minHeight > 0 && maxHeight > 0 && minHeight > maxHeight) {
            FormValidateUtils.Return(string.Format(result, "3"));
            return;
        }

        if (minWeight > 0 && maxWeight > 0 && minWeight > maxWeight) {
            FormValidateUtils.Return(string.Format(result, "4"));
            return;
        }

        IUserGeneralCondition _objectGeneralCondition = StructureMapFactory.GetInstance<IUserGeneralCondition>();
        UserGeneralConditionEnt generalCondition = _objectGeneralCondition.GetByUserKey(userContext.UserKey);
        if(generalCondition == null) {
            generalCondition = new UserGeneralConditionEnt();

            generalCondition.UserKey = userContext.UserKey;
            generalCondition.OldMin = minOld;
            generalCondition.OldMax = maxOld;
            generalCondition.HeightMin = minHeight;
            generalCondition.HeightMax = maxHeight;
            generalCondition.WeightMin = minWeight;
            generalCondition.WeightMax = maxWeight;
            generalCondition.Income = inCome;
            generalCondition.CityIDs = cityID;
            generalCondition.JobIDs = jobID;
            generalCondition.EducationID = educationID;
            generalCondition.ReligionID = religionID;
            generalCondition.MaritalStatusID = maritalStatusID;
            generalCondition.SmokingID = smokingID;
            if(!_objectGeneralCondition.Insert(generalCondition)) {
                FormValidateUtils.Return(string.Format(result, "0"));
                return;
            }
        }
        else {
            generalCondition.OldMin = minOld;
            generalCondition.OldMax = maxOld;
            generalCondition.HeightMin = minHeight;
            generalCondition.HeightMax = maxHeight;
            generalCondition.WeightMin = minWeight;
            generalCondition.WeightMax = maxWeight;
            generalCondition.Income = inCome;
            generalCondition.CityIDs = cityID;
            generalCondition.JobIDs = jobID;
            generalCondition.EducationID = educationID;
            generalCondition.ReligionID = religionID;
            generalCondition.MaritalStatusID = maritalStatusID;
            generalCondition.SmokingID = smokingID;
            if (!_objectGeneralCondition.Update(generalCondition)) {
                FormValidateUtils.Return(string.Format(result, "0"));
                return;
            }
        }

        FormValidateUtils.Return(string.Format(result, "1"));
    }

    private void SaveBlast(HttpContext context) {
        string result = "{{\"result\":\"{0}\"}}";
        string content = Commons.StripAllTag(context.Request.Form["content"]);
        if (BabWordFilter.ContainsBadWords(content)) {
            FormValidateUtils.Return(string.Format(result, "3"));
            return;
        }
        content = Commons.BreakWords(content, 10);
        UserContext userContext = LoginFactory.GetCurrentUser();
        if (userContext == null) {
            FormValidateUtils.Return(string.Format(result, "-1"));
            return;
        }
        if (content.Length > 0 && content.Length <= AppSettings.LengthBlast) {
            IUserGeneralProfile iUserGeneralProfile = StructureMapFactory.GetInstance<IUserGeneralProfile>();
            UserGeneralProfileEnt userGeneralProfileEnt = iUserGeneralProfile.GetByUserKey(userContext.UserKey);
            userGeneralProfileEnt.Blast = content;
            if (iUserGeneralProfile.UpdateBlast(userGeneralProfileEnt))
                FormValidateUtils.Return(string.Format(result, "1"));
            else
                FormValidateUtils.Return(string.Format(result, "0"));
        }
        else
            FormValidateUtils.Return(string.Format(result, "2"));

    }
        

    private void UploadImages(HttpContext context) {
        int result = 0;
        UserContext userContext = LoginFactory.GetCurrentUser();
        try {
            if (userContext == null) {
                result = -1;
            }

            if (StructureMapFactory.GetInstance<IUserImage>().GetCountByUserKey(userContext.UserKey) >= AppSettings.ImageLimit) {
                result = -3;
                return;
            }

            string ext = string.Empty;
            string fileName = string.Empty;
            System.IO.Stream st = null;

            int imageCount = context.Request.Files.Count;
            if (imageCount > 5)
                imageCount = 5;

            int index = -1;
            int imageUploadSuccessCount = 0;
            for (int i = 0; i < imageCount; i++) {
                if (!string.IsNullOrEmpty(context.Request.Files[i].FileName)) {
                    ext = "";
                    fileName = context.Request.Files[i].FileName;

                    index = fileName.LastIndexOf(".");

                    if (index > 0) {
                        ext = fileName.Substring(index);
                        fileName = fileName.Substring(0, index);
                    }
                    if (!fileTypes.Contains(ext.ToLower())) {
                        continue;
                    }

                    if (context.Request.Files[0].ContentLength > MaxFileSizeUpload) {
                        continue;
                    }

                    st = context.Request.Files[i].InputStream;

                    if (ImageUploadHandle(context, userContext.UserKey, userContext.DateCreated, st) == EUploadImageResult.Success) {
                        imageUploadSuccessCount++;
                    }
                }
            }
            result = imageUploadSuccessCount;
        }
        catch {
            result = -2;
        }
        finally{
            if (userContext != null) {
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.Write("<script type='text/javascript'>");
                HttpContext.Current.Response.Write("window.parent.uploadImagesComplete('" + result + "');window.close();");
                HttpContext.Current.Response.Write("</script>");
            }
        }
    }

    /// <summary>
    /// -1: Chưa đăng nhập
    /// 1: Xóa thành công
    /// 2: Không đúng ID
    /// 0: Lỗi hệ thống
    /// </summary>
    /// <param name="context"></param>
    private void DeleteImage(HttpContext context) {
        string result = "{{\"result\":\"{0}\"}}";
        UserContext userContext = LoginFactory.GetCurrentUser();

        if (userContext == null) {
            FormValidateUtils.Return(string.Format(result, "-1"));
            return;
        }

        long imageID = ConvertUtils.ToLong(context.Request.Form["id"]);

        IUserImage _objectImage = StructureMapFactory.GetInstance<IUserImage>();

        UserImageEnt imageEnt = _objectImage.GetByUserKeyAndID(userContext.UserKey, imageID);

        if (imageEnt == null) {
            FormValidateUtils.Return(string.Format(result, "0")); ;
            return;
        }

        string imageFolderPath = userContext.UserKey + "/Images/";
        string imagePath = context.Server.MapPath(@"/res/images/users/") + imageEnt.FileName;
        string imageThumbPath = context.Server.MapPath(@"/res/images/users/") + imageEnt.ThumbFileName;

        if (!FileUtils.Delete(imagePath)) {
            FormValidateUtils.Return(string.Format(result, "0"));
            return;
        }
        if (!FileUtils.Delete(imageThumbPath)) {
            FormValidateUtils.Return(string.Format(result, "0"));
            return;
        }

        if (!_objectImage.Delete(imageID, userContext.UserKey)) {
            FormValidateUtils.Return(string.Format(result, "0"));
            return;
        }
        FormValidateUtils.Return(string.Format(result, "1"));
    }

    /// <summary>
    /// -1: Chưa đăng nhập
    /// 0: Lỗi hệ thống
    /// 1: Thành công
    /// 2: Kích thước không phù hợp
    /// 3: Tỉ lệ không phù hợp
    /// </summary>
    /// <param name="context"></param>
    private void ChangeAvatarByImage(HttpContext context) {
        string result = "{{\"result\":\"{0}\"}}";
        UserContext userContext = LoginFactory.GetCurrentUser();
        if (userContext == null) {
            FormValidateUtils.Return(string.Format(result, "-1"));
            return;
        }
        int x = ConvertUtils.ToInt(context.Request.Form["x"], -1);
        int y = ConvertUtils.ToInt(context.Request.Form["y"], -1);
        int w = ConvertUtils.ToInt(context.Request.Form["w"], -1);
        int h = ConvertUtils.ToInt(context.Request.Form["h"], -1);
        long imageId = ConvertUtils.ToLong(context.Request.Form["id"], -1);
        if(x == -1 || y == -1 || w <= 0 || h <= 0 || imageId <= 0) {
            FormValidateUtils.Return(string.Format(result, "2"));
            return;
        }
        UserImageEnt imageEnt = StructureMapFactory.GetInstance<IUserImage>().GetByUserKeyAndID(userContext.UserKey, imageId);
        if (imageEnt == null) {
            FormValidateUtils.Return(string.Format(result, "0"));
            return;
        }
        string imageUrl = AppSettings.ImageStoreUploadServer + imageEnt.FileName;
        System.Net.WebClient urlGrabber = new System.Net.WebClient();
        byte[] data = urlGrabber.DownloadData(imageUrl);
        if (data == null || data.Length == 0) {
            FormValidateUtils.Return(string.Format(result, "0"));
            return;
        }
        System.IO.Stream originalStream = new System.IO.MemoryStream(data);
        System.IO.Stream croppedStream = null;
        if (NCT.Framework.ImageUtils.Split(originalStream, x, y, w, h, w, h, out croppedStream)) {
            EUploadImageResult handleResult = AvatarUploadHandle(context, userContext.UserKey, userContext.DateCreated, croppedStream);
            switch (handleResult) {
                case EUploadImageResult.SystemError:
                    FormValidateUtils.Return(string.Format(result, "0")); // system error
                    break;
                case EUploadImageResult.InvalidHeight:
                    FormValidateUtils.Return(string.Format(result, "3"));
                    break;
                case EUploadImageResult.InvalidWidth:
                    FormValidateUtils.Return(string.Format(result, "3"));
                    break;
                default:
                    FormValidateUtils.Return(string.Format(result, "1"));
                    break;        
            }
        }
        else {
            FormValidateUtils.Return(string.Format(result, "0"));
        }
    }

    /// <summary>
    /// Send Messages
    /// -1: Chưa Đăng nhập
    /// 1: Gửi tin nhắn thành công
    /// 2: Tiêu Đề Rỗng
    /// 3: Nội dung rỗng
    /// 4: Không tồn tại người nhận
    /// 5: Không có quyền gửi tin
    /// 6: Không thể gửi đến chính mình
    /// 7: Không thể gửi quá 3 tin nhắn mà không được trả lời
    /// 0: Lỗi hệ thống

    public void SendMessage(HttpContext context) {
        UserContext userContext = LoginFactory.GetCurrentUser();
        string result = "{{\"result\":\"{0}\"}}";

        if (userContext == null) {
            FormValidateUtils.Return(string.Format(result, "-1"));
            return;
        }

        if ((userContext.Status & EUserStatus.Verified) != EUserStatus.Verified) {
            FormValidateUtils.Return(string.Format(result, "5"));
            return;
        }

        string messageTitle = Commons.StripAllTag(ConvertUtils.ToString(context.Request.Form["messageTitle"]));
        messageTitle = Commons.BreakWords(messageTitle, 10);
        messageTitle = messageTitle.Trim();
        string messageContent = Commons.StripAllTag(ConvertUtils.ToString(context.Request.Form["messageContent"]));
        if (BabWordFilter.ContainsBadWords(messageContent)) {
            FormValidateUtils.Return(string.Format(result, "8", "", "", "", ""));
            return;
        }
        messageContent = Commons.BreakWords(messageContent, 10);
        messageContent = Commons.HtmlCharEncode(messageContent);
        messageContent = messageContent.Trim();
        messageContent = messageContent.Replace("\n", "<br />");
        string receiverUserKey = ConvertUtils.ToString(context.Request.Form["receiverUserKey"]);

        IUserMessage _objectUserMessage = StructureMapFactory.GetInstance<IUserMessage>();

        if (userContext.UserKey == receiverUserKey) {
            FormValidateUtils.Return(string.Format(result, "6"));
            return;
        }

        if(!_objectUserMessage.CheckUser1CanSendMessageToUser2(userContext.UserKey, receiverUserKey)){
            FormValidateUtils.Return(string.Format(result, "7"));
            return;
        }

        if (messageTitle == "") {
            FormValidateUtils.Return(string.Format(result, "2"));
            return;
        }
        if (messageContent == "") {
            FormValidateUtils.Return(string.Format(result, "3"));
            return;
        }

        IUser _objectUser = StructureMapFactory.GetInstance<IUser>();
        if(_objectUser.GetByUserKey(receiverUserKey) == null) {
            FormValidateUtils.Return(string.Format(result, "4"));
            return;
        }

        UserMessageEnt messageEnt = new UserMessageEnt();

        messageEnt.Title = messageTitle;
        messageEnt.Content = messageContent;
        messageEnt.ReceivedUserKey = receiverUserKey;
        messageEnt.SentUserKey = userContext.UserKey;
        if (!_objectUserMessage.InsertConversation(messageEnt)) {
            FormValidateUtils.Return(string.Format(result, "0"));
            return;
        }

        FormValidateUtils.Return(string.Format(result, "1"));
    }
    //End Send Message

    /// <summary>
    /// -1: Chưa đăng nhập
    /// 1: Xóa thành công
    /// 2: Không dúng ConversationID
    /// 0: Lỗi hệ thống
    /// </summary>
    /// <param name="context"></param>
    public void DeleteConversation(HttpContext context) {
        string result = "{{\"result\":\"{0}\"}}";
        UserContext userContext = LoginFactory.GetCurrentUser();

        if (userContext == null) {
            FormValidateUtils.Return(string.Format(result, "-1"));
            return;
        }
        long conversationId = ConvertUtils.ToLong(context.Request.Form["conversationId"]);

        if (!StructureMapFactory.GetInstance<IUserMessage>().DeleteConversation(userContext.UserKey, conversationId)) {
            FormValidateUtils.Return(string.Format(result, "0"));
            return;
        }
        FormValidateUtils.Return(string.Format(result, "1"));
    }

    /// <summary>
    /// -1: Chưa đăng nhập
    /// 1: Xóa thành công
    /// 2: Không dúng MessageID
    /// 0: Lỗi hệ thống
    /// </summary>
    /// <param name="context"></param>
    public void DeleteMessage(HttpContext context) {
        string result = "{{\"result\":\"{0}\"}}";
        UserContext userContext = LoginFactory.GetCurrentUser();

        if (userContext == null) {
            FormValidateUtils.Return(string.Format(result, "-1"));
            return;
        }
        long messageID = ConvertUtils.ToLong(context.Request.Form["messageID"]);
        string delType = context.Request.Form["delType"];
        bool res;

        if (delType == "s") {
            res = StructureMapFactory.GetInstance<IUserMessage>().SenderDeleteMessage(userContext.UserKey, messageID);
        }
        else if (delType == "r") {
            res = StructureMapFactory.GetInstance<IUserMessage>().ReceiverDeleteMessage(userContext.UserKey, messageID);
        }
        else {
            FormValidateUtils.Return(string.Format(result, "2"));
            return;
        }

        if (res == true) {
            FormValidateUtils.Return(string.Format(result, "1"));
        }
        else {
            FormValidateUtils.Return(string.Format(result, "0"));
        }
    }

    /// <summary>
    /// Reply Messages
    /// -1: Chưa đăng nhập
    /// 1: Gửi thành công
    /// 2: Không tồn tại cuộc hội thoại trên
    /// 3: Nội dung rỗng
    /// 4: Không thể gửi quá 3 tin nhắn mà không được trả lời
    /// 0: Lỗi hệ thống
    public void ReplyMessage(HttpContext context) {
        UserContext userContext = LoginFactory.GetCurrentUser();
        string result = "{{\"result\":\"{0}\",\"newID\":\"{1}\",\"senderName\":\"{2}\",\"shortContent\":\"{3}\",\"Content\":\"{4}\"}}";

        if (userContext == null) {
            FormValidateUtils.Return(string.Format(result, "-1", "", "", "", ""));
            return;
        }

        long conversationID = ConvertUtils.ToLong(context.Request.Form["conversationID"]);
        string messageContent = Commons.StripAllTag(context.Request.Form["messageContent"]);
        messageContent = Commons.HtmlCharEncode(messageContent);
        if (BabWordFilter.ContainsBadWords(messageContent)) {
            FormValidateUtils.Return(string.Format(result, "5", "", "", "", ""));
            return;
        }
        messageContent = Commons.BreakWords(messageContent, 10);
        messageContent = messageContent.Trim();
        messageContent = messageContent.Replace("\n", "<br />");
        
        if (messageContent == string.Empty) {
            FormValidateUtils.Return(string.Format(result, "3", "", "", "", ""));
            return;
        }

        IUserMessage _objectMessage = StructureMapFactory.GetInstance<IUserMessage>();
        UserMessageEnt conversation = _objectMessage.GetConversation(userContext.UserKey, conversationID);
        if(conversation == null) {
            FormValidateUtils.Return(string.Format(result, "2", "", "", "", ""));
            return;
        }

        bool canSendMessage = true;
        if (conversation.SentUserKey == userContext.UserKey) {
            canSendMessage = _objectMessage.CheckUser1CanSendMessageToUser2(userContext.UserKey, conversation.ReceivedUserKey);
        }
        else {
            canSendMessage = _objectMessage.CheckUser1CanSendMessageToUser2(userContext.UserKey, conversation.SentUserKey);
        }
        
        if(!canSendMessage) {
            FormValidateUtils.Return(string.Format(result, "4", "", "", "", ""));
            return;
        }
        
        UserMessageEnt messageEnt = new UserMessageEnt();

        messageEnt.ConversationID = conversationID;
        messageEnt.Title = conversation.Title;
        messageEnt.Content = messageContent;
        if (conversation.SentUserKey == userContext.UserKey) {
            messageEnt.ReceivedUserKey = conversation.ReceivedUserKey;
        }
        else {
            messageEnt.ReceivedUserKey = conversation.SentUserKey;
        }
        messageEnt.SentUserKey = userContext.UserKey;
        if(!_objectMessage.InsertMessage(messageEnt)) {
            FormValidateUtils.Return(string.Format(result, "0", "", "", "", ""));
            return;
        }
        int index = messageContent.IndexOf("<br />");
        string shortContent = string.Empty;
        if (index >= 0) {
            shortContent = StringUtils.CutStringChar(messageContent.Substring(0, index), 70);
        }
        else {
            shortContent = StringUtils.CutStringChar(messageContent, 70);
        }

        FormValidateUtils.Return(string.Format(result, "1", messageEnt.ID, userContext.FullName, shortContent, messageContent));
    }
    
    /// <summary>
    /// 1: Gửi thành công
    /// -1: Chưa đăng nhập
    /// 2: Không thể báo vi phạm chính mình
    /// 3: Chưa cung cấp lý do
    /// 4: Chưa được duyệt tài khoản
    /// 0: Lỗi hệ thống
    /// </summary>
    /// <param name="context"></param>
    private void SendReport(HttpContext context) {
        UserContext userContext = LoginFactory.GetCurrentUser();
        string result = "{{\"result\":\"{0}\"}}";
        if(userContext == null) {
            FormValidateUtils.Return(string.Format(result, "-1"));
            return;
        }
        
        string reportedUserKey = ConvertUtils.ToString(context.Request.Form["reportedUserKey"]);
        string reason = Commons.StripAllTag(context.Request.Form["reason"]);
        reason = Commons.HtmlCharEncode(reason);

        if ((userContext.Status & EUserStatus.Verified) != EUserStatus.Verified) {
            FormValidateUtils.Return(string.Format(result, "4"));
            return;
        }
        
        if(reportedUserKey == userContext.UserKey) {
            FormValidateUtils.Return(string.Format(result, "2"));
            return;
        }
        
        if(reason == "") {
            FormValidateUtils.Return(string.Format(result, "3"));
        }

        UserReportEnt item = new UserReportEnt();
        item.UserKey = userContext.UserKey;
        item.ReportedUserKey = reportedUserKey;
        item.Reason = reason;
        
        if(!StructureMapFactory.GetInstance<IUserReport>().Insert(item)) {
            FormValidateUtils.Return(string.Format(result, "0"));
            return;
        }

        FormValidateUtils.Return(string.Format(result, "1"));
    }
    
    private void AddFollow(HttpContext context) {
        UserContext userContext = LoginFactory.GetCurrentUser();
        string result = "{{\"result\":\"{0}\"}}";
        if (userContext == null) {
            FormValidateUtils.Return(string.Format(result, "-1"));
            return;
        }

        if ((userContext.Status & EUserStatus.Verified) != EUserStatus.Verified) {
            FormValidateUtils.Return(string.Format(result, "4"));
            return;
        }

        string followedUserKey = ConvertUtils.ToString(context.Request.Form["followedUserKey"]);

        if (followedUserKey.Length == 0) {
            FormValidateUtils.Return(string.Format(result, "2"));
            return;
        }
        
        if(followedUserKey == userContext.UserKey) {
            FormValidateUtils.Return(string.Format(result, "3"));
            return;
        }
        
        if(StructureMapFactory.GetInstance<IUserGeneralProfile>().GetByUserKey(followedUserKey) == null) {
            FormValidateUtils.Return(string.Format(result, "2"));
            return;
        }

        IUserFollower _objFollower = StructureMapFactory.GetInstance<IUserFollower>();

        if (_objFollower.CheckExist(userContext.UserKey, followedUserKey)) {
            FormValidateUtils.Return(string.Format(result, "5"));
            return;
        }

        if (_objFollower.CountByFollowerUserKey(userContext.UserKey) ==AppSettings.FollowerLimit)
        {
            FormValidateUtils.Return(string.Format(result, "6"));
            return;
        }  
        
        UserFollowerEnt item = new UserFollowerEnt();
        item.FollowerUserKey = userContext.UserKey;
        item.FollowedUserKey = followedUserKey;
        if (!_objFollower.Insert(item)) {
            FormValidateUtils.Return(string.Format(result, "0"));
            return;
        }

        FormValidateUtils.Return(string.Format(result, "1"));
    }
    
    /// <summary>
    /// 1: Xóa thành công
    /// -1: Chưa Đăng nhập
    /// 2: UserKey người được theo không hợp lệ
    /// 0: Lỗi hệ thống
    /// </summary>
    /// <param name="context"></param>
    private void DeleteFollow(HttpContext context) {
        UserContext userContext = LoginFactory.GetCurrentUser();
        string result = "{{\"result\":\"{0}\"}}";
        if (userContext == null) {
            FormValidateUtils.Return(string.Format(result, "-1"));
            return;
        }
        string followedUserKey = ConvertUtils.ToString(context.Request.Form["followedUserKey"]);
        
        if(followedUserKey.Length == 0) {
            FormValidateUtils.Return(string.Format(result, "2"));
            return;
        }
        
        if(!StructureMapFactory.GetInstance<IUserFollower>().Delete(userContext.UserKey, followedUserKey)) {
            FormValidateUtils.Return(string.Format(result, "0"));
            return;
        }
        
        FormValidateUtils.Return(string.Format(result, "1"));
    }

    /// <summary>
    /// Save password
    /// -1: Chưa đăng nhập
    /// 1: thay đổi status thành công
    /// 2: Chua nhập captcha
    /// 3: captcha không đúng
    /// 0: Lỗi hệ thống
    /// </summary>
    /// <param name="context"></param>
    private void ChangeStatus(HttpContext context)
    {
        UserContext userContext = LoginFactory.GetCurrentUser();
        string result = "{{\"result\":\"{0}\"}}";

        if (userContext == null)
        {
            result = "{{\"result\":\"{0}\"}}";
            FormValidateUtils.Return(string.Format(result, "-1", AppSettings.RootURL + "login"));
            return;
        }

        bool isHideProfile =ConvertUtils.ToBool(context.Request.Form["isHileProfile"]);
        string captCha = context.Request.Form["captcha"];
        
        if (context.Session[AppSettings.SESSION_ANTISPAMTEXT] != null)
        {
            string code = captCha;
            if (code.Equals(""))
            {
                FormValidateUtils.Return(string.Format(result, "2"));//khong nhap captcha
                return;
            }
            else if (!code.ToLower().Equals(context.Session[AppSettings.SESSION_ANTISPAMTEXT].ToString().ToLower()))
            {
                FormValidateUtils.Return(string.Format(result, "3"));//sai captcha
                return;
            }
            else
                context.Session.Remove(AppSettings.SESSION_ANTISPAMTEXT);
        }

        IUser _objectUser = StructureMapFactory.GetInstance<IUser>();
        UserEnt userEnt = null;
        userEnt = _objectUser.GetByUserKey(userContext.UserKey);
        if (userEnt == null)
        {
            FormValidateUtils.Return(string.Format(result, "0"));
            return;
        }
        if (isHideProfile)
        {
            if (!_objectUser.Hide(userEnt.UserKey))
            {
                FormValidateUtils.Return(string.Format(result, "0"));
            }
            userContext.Status = userContext.Status | EUserStatus.Hidden;
        }
        else
        {
            if (!_objectUser.UnHide(userEnt.UserKey))
            {
                FormValidateUtils.Return(string.Format(result, "0"));
            }
            userContext.Status = userContext.Status ^ (EUserStatus.Hidden & userContext.Status);
        }        
        LoginFactory.SetUserSession(userContext);
        FormValidateUtils.Return(string.Format(result, "1"));
    }

    private void ReturnForRegister(string result) {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Write("<script type='text/javascript'>");
        HttpContext.Current.Response.Write("window.parent.registerComplete('" + result + "');window.close();");
        HttpContext.Current.Response.Write("</script>");
    }

    private static void RedirectToLoginPage() {
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.Write("<script type='text/javascript'>");
        HttpContext.Current.Response.Write("window.location = '/login';");
        HttpContext.Current.Response.Write("</script>");
    }

    enum EUploadImageResult {
        SystemError = 0,
        Success = 1,
        InvalidHeight = 2,
        InvalidWidth = 3,
        InvalidFileExtension = 4,
        InvalidFileSize = 5,
        InvalidImageSize = 6,
        EmptyFileError = 7
    }

    private EUploadImageResult AvatarUploadHandle(HttpContext context, string userKey, DateTime dateCreated, System.IO.Stream st) {

        System.IO.Stream stOutAvatar;
        System.IO.Stream stOutAvatarThumbBeforeScale;
        System.IO.Stream stOutAvatarThumb;

        string ext = ".jpg";
        string longTick = DateTime.Now.Ticks.ToString();
        string avatarName = userKey + ext;
        string avatarThumbName = userKey + "-thumb" + ext;

        string avatarFolderPath = "avatar/" + dateCreated.Year + "/" + dateCreated.Month + "/" + dateCreated.Day + "/";

        //string stName = userKey + "/FullAvatar/" + userKey + "-" + longTick + ext;
        //string stOutAvatarName = userKey + "/Avatar/" + userKey + ext;
        //string stOutAvatarThumbName = userKey + "/Avatar/" + userKey + "-thumb" + ext;

        //Scale Avatar Image
        NCT.Framework.ImageScaleResult rsAvatar = NCT.Framework.ImageUtils.Scale(st, 100, 100, AppSettings.AvatarWidth, AppSettings.AvatarHeight, 1, false, out stOutAvatar);
        if (rsAvatar == ImageScaleResult.Success) {
            //Calculate for size of avatar thumb image (before scale)
            ImageInfo avatarInfo = NCT.Framework.ImageUtils.GetInfo(stOutAvatar);
            int x = 0;
            int y = 0;
            int w = 0;
            int h = 0;
            if (avatarInfo.Width > avatarInfo.Height) {
                w = h = avatarInfo.Height;
                x = (avatarInfo.Width - avatarInfo.Height) / 2;
            }
            else {
                w = h = avatarInfo.Width;
                y = (avatarInfo.Height - avatarInfo.Width) / 2;
            }
            stOutAvatar.Seek(0, System.IO.SeekOrigin.Begin);
            if (NCT.Framework.ImageUtils.Split(stOutAvatar, x, y, w, h, w, h, out stOutAvatarThumbBeforeScale)) {
                stOutAvatarThumbBeforeScale.Seek(0, System.IO.SeekOrigin.Begin);
                NCT.Framework.ImageScaleResult rsAvatarThumb = NCT.Framework.ImageUtils.Scale(stOutAvatarThumbBeforeScale, 100, 100, AppSettings.AvatarThumbWidth, AppSettings.AvatarThumbHeight, 1, false, out stOutAvatarThumb);
                if (rsAvatarThumb == ImageScaleResult.Success) {
                    stOutAvatarThumb.Seek(0, System.IO.SeekOrigin.Begin);
                    //if (!FtpUtils.Upload(AppSettings.FtpUploadServer, AppSettings.FtpUploadUser, AppSettings.FtpUploadPassword, stOutAvatarThumb, AppSettings.FtpUploaFolder, stOutAvatarThumbName)) {
                    //    return EUploadAvatarResult.SystemError;
                    //}
                    if (!SaveStreamToImageFile(avatarFolderPath, avatarThumbName, stOutAvatarThumb, context)) {
                        return EUploadImageResult.SystemError;
                    }
                }
                else if (rsAvatarThumb == ImageScaleResult.InvalidWidth) {
                    return EUploadImageResult.InvalidWidth;
                }
                else if (rsAvatarThumb == ImageScaleResult.UnKnown) {
                    return EUploadImageResult.SystemError;
                }
            }
            else {
                return EUploadImageResult.SystemError;
            }

            stOutAvatar.Seek(0, System.IO.SeekOrigin.Begin);
            //if (!FtpUtils.Upload(AppSettings.FtpUploadServer, AppSettings.FtpUploadUser, AppSettings.FtpUploadPassword, stOutAvatar, AppSettings.FtpUploaFolder, stOutAvatarName)) {
            //    return EUploadAvatarResult.SystemError;
            //}
            if (!SaveStreamToImageFile(avatarFolderPath, avatarName, stOutAvatar, context)) {
                return EUploadImageResult.SystemError;
            }

            //Insert Avatar
            IUserAvatar iUserAvatar = StructureMapFactory.GetInstance<IUserAvatar>();

            UserAvatarEnt userAvatarEnt = iUserAvatar.GetByUserKey(userKey);

            if (userAvatarEnt == null) {
                userAvatarEnt = new UserAvatarEnt();
                userAvatarEnt.DateCreated = DateTime.Now;
                userAvatarEnt.Status = EUserAvatarStatus.Available;
                userAvatarEnt.FileName = avatarFolderPath + avatarName;
                userAvatarEnt.UserKey = userKey;
                iUserAvatar.Insert(userAvatarEnt);
            }
            else {
                userAvatarEnt.FileName = avatarFolderPath + avatarName;
                userAvatarEnt.Status = EUserAvatarStatus.Available;
                iUserAvatar.Update(userAvatarEnt);
            }
        }
        else if (rsAvatar == ImageScaleResult.InvalidHeight) {
            return EUploadImageResult.InvalidHeight;
        }
        else if (rsAvatar == ImageScaleResult.InvalidWidth) {
            return EUploadImageResult.InvalidWidth;
        }
        else if (rsAvatar == ImageScaleResult.UnKnown) {
            return EUploadImageResult.SystemError;
        }
        return EUploadImageResult.Success;
    }

    private EUploadImageResult ImageUploadHandle(HttpContext context, string userKey, DateTime dateCreated, System.IO.Stream st) {
        string ext = ".jpg";
        string imageName = string.Empty;
        string imageThumbName = string.Empty;
        ImageScaleResult rsImage = ImageScaleResult.UnKnown;
        ImageScaleResult rsThumbImage = ImageScaleResult.UnKnown;
        System.IO.Stream stOutImage = null;
        System.IO.Stream stOutImageThumb = null;

        string longTick = DateTime.Now.Ticks.ToString();
        imageName = userKey + "-" + longTick + ext;
        imageThumbName = userKey + "-" + longTick + "-thumb" + ext;

        string imageFolderPath = "photo/" + dateCreated.Year + "/" + dateCreated.Month + "/" + dateCreated.Day + "/";

        rsImage = ImageUtils.Scale(st, 100, 100, AppSettings.ImageWidth, AppSettings.ImageHeight, 1, false, out stOutImage);

        if (rsImage == ImageScaleResult.Success) {
            st.Seek(0, System.IO.SeekOrigin.Begin);
            rsThumbImage = ImageUtils.Scale(st, 50, 50, AppSettings.ImageThumbWidth, AppSettings.ImageThumbHeight, 1, false, out stOutImageThumb);

            if (rsThumbImage == ImageScaleResult.Success) {
                stOutImageThumb.Seek(0, System.IO.SeekOrigin.Begin);
                //if (!FtpUtils.Upload(AppSettings.FtpUploadServer, AppSettings.FtpUploadUser, AppSettings.FtpUploadPassword, stOutImageThumb, AppSettings.FtpUploaFolder, stOutImageThumbName)) {
                //    continue;
                //}
                if (!SaveStreamToImageFile(imageFolderPath, imageThumbName, stOutImageThumb, context)) {
                    return EUploadImageResult.SystemError;
                }

                stOutImage.Seek(0, System.IO.SeekOrigin.Begin);
                //if (!FtpUtils.Upload(AppSettings.FtpUploadServer, AppSettings.FtpUploadUser, AppSettings.FtpUploadPassword, stOutImage, AppSettings.FtpUploaFolder, stOutImageName)) {
                //    continue;
                //}
                if (!SaveStreamToImageFile(imageFolderPath, imageName, stOutImage, context)) {
                    return EUploadImageResult.SystemError;
                }

                //Insert Image
                IUserImage iUserImage = StructureMapFactory.GetInstance<IUserImage>();

                UserImageEnt userImageEnt = new UserImageEnt();

                userImageEnt.DateCreated = DateTime.Now;
                userImageEnt.FileName = imageFolderPath + imageName;
                userImageEnt.ThumbFileName = imageFolderPath + imageThumbName;
                userImageEnt.UserKey = userKey;
                if (!iUserImage.Insert(userImageEnt)) {
                    return EUploadImageResult.SystemError;
                }
            }
        }
        return EUploadImageResult.Success;
    }

    private bool SaveStreamToImageFile(string folderPath, string imageName, System.IO.Stream inputStream, HttpContext context) {
        bool result = true;
        try {
            string fullFolderPath = context.Server.MapPath(@"/res/images/users/") + folderPath;
            if (!FileUtils.CreateFolderForFile(fullFolderPath)){
                return false;
            }
            fullFolderPath += "/";
            // Create a FileStream object to write a stream to a file
            using (System.IO.FileStream fileStream = System.IO.File.Create(fullFolderPath + imageName, (int)inputStream.Length)) {
                // Fill the bytes[] array with the stream data
                byte[] bytesInStream = new byte[inputStream.Length];
                inputStream.Read(bytesInStream, 0, (int)bytesInStream.Length);

                // Use FileStream object to write to the specified file
                fileStream.Write(bytesInStream, 0, bytesInStream.Length);
            }
        }
        catch (SystemException ex) {
            result = false;
        }
        return result;
    }
    

    public bool IsReusable {
        get {
            return false;
        }
    }
}
